package com.annet.token.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * Create by panlin on 2016年1月5日
 */
public final class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    public static ObjectMapper getInstance() {
        if (mapper != null) {
            return mapper;
        } else {
            return new ObjectMapper();
        }
    }

    /**
     * bean转换为Json字符串
     *
     * @param obj
     * @return
     */
    public static String bean2Json(Object obj) {
        ObjectMapper objectMapper = JsonUtil.getInstance();
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Json字符串转换为实体类bean
     *
     * @param jsonStr
     * @param objClass
     * @return
     */
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        ObjectMapper mapper = JsonUtil.getInstance();
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     *
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = mapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 初始化Json字符串
     *
     * @param JsonStr
     * @return
     */
    public static JsonNode InitJson(String JsonStr) {
        try {
            ObjectMapper mapper = JsonUtil.getInstance();
            JsonNode root = mapper.readTree(JsonStr);
            return root;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String prettyFormat(Object object) {
        return JSON.toJSONString(object,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
    }
}
